package com.back.utils;

import com.back.excepction.BaseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
@Slf4j
public class JacksonUtils {
    static ObjectMapper objectMapper = new ObjectMapper();
    static {
        //忽略json中的多余属性（java对象中不存在的对象）
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    static public String objectToJson(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("对象转json出现异常");
            throw new BaseException("对象转json出现异常");
        }
    }

    static public <T> T jsonToObject(String s, Class<T> c) throws JsonProcessingException {
        T t = objectMapper.readValue(s, c);
        return t;
    }


 /*    static public <T> List<T> jsonToList(String s, Class<T> c) {
        try {
            return objectMapper.readValue(s, new TypeReference<List<T>>(){});
        } catch (JsonProcessingException e) {
            log.error("json转对象出现异常");
            throw new BaseException("json转对象出现异常");
        }
    }   */

    static public <T> List<T> jsonToList(String s, Class<T> c) {
        try {
            // 先检查json是否是数组格式
            JsonNode rootNode = objectMapper.readTree(s);
            if (!rootNode.isArray()) {
                throw new BaseException("JSON不是数组格式");
            }

            // 使用constructCollectionType确保类型安全
            JavaType type = objectMapper.getTypeFactory()
                    .constructCollectionType(List.class, c);
            return objectMapper.readValue(s, type);
        } catch (JsonProcessingException e) {
            log.error("json转对象出现异常");
            throw new BaseException("json转对象出现异常");
        }
    }
}
